﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HtmlAgilityPack;

namespace xuptlibsearch
{
    public partial class detail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "UTF-8";
            Response.ContentType = "text/json";
            string id = Request.Params["id"];
            string barcode = Request.Params["barcode"];
            if ((id == "" || id == null) && (string.IsNullOrWhiteSpace(barcode)))
            {
                Response.Write("Param_Error");
                return;
            }
            else if (!string.IsNullOrWhiteSpace(barcode) && string.IsNullOrWhiteSpace(id))
            {
                id = GetID(barcode);
            }
            GetInfo(id);
        }

        string GetID(string barcode)
        {
            string param = string.Format("search_no_type=Y&snumber_type=Y&suchen_type=7&suchen_word={0}&suchen_match=qx&recordtype=all&library_id=all&show_type=wenzi&B1=%C8%B7%B6%A8", barcode);
            byte[] bin = Encoding.ASCII.GetBytes(param);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://222.24.3.7:8080/opac_two/search2/searchout.jsp");
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            using(Stream stream = req.GetRequestStream())
            {
                stream.Write(bin, 0, bin.Length);
            }
            string content = "";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            using(Stream stream = res.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
                content = reader.ReadToEnd();
            }
            if(content.Contains("<div id=\"no_text\">"))
            {
                return null;
            }
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(content);
            HtmlNode node = doc.GetElementbyId("searchout_tuwen");
            string link = node.ChildNodes["table"].SelectNodes("//a[@target='_blank']")[0].Attributes["href"].Value;
            link = link.Replace("s_detail.jsp?sid=", "");
            
            return link;
        }

        private void GetInfo(string id)
        {
            string str = "";
            try
            {
                WebRequest req = WebRequest.Create("http://222.24.3.7:8080/book/ssdetailBook.jsp?rec_ctrl_id=" + id);
                req.Timeout = 30000;
                WebResponse rp = req.GetResponse();
                Stream st = rp.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("gb2312"));
                str = reader.ReadToEnd();
            }
            catch
            {
                Response.Write("Server_Error");
                return;
            }

            if (str.Contains("该书无详细信息"))
            {
                Response.Write("null");
                return;
            }

            str = str.Substring(str.IndexOf("书名与责任者项 : "));
            string tmp = str.Substring(str.IndexOf(":: 关联记录 ::"));
            str = str.Replace(tmp, "");

            string title = str = str.Substring(20);
            tmp = title.Substring(title.IndexOf("</td>"));
            title = title.Replace(tmp, "");
            string[] temp = Regex.Split(title, " / ");
            title = temp[0];
            string author = temp[1];

            string pub = "";
            if (str.Contains("标准书号"))
            {
                if (str.Contains("出版者"))
                {
                    pub = str = str.Substring(str.IndexOf("出版者 : "));
                    tmp = pub.Substring(pub.IndexOf("</td>\n</tr>\n<tr  >"));
                    pub = pub.Replace(tmp, "");
                    pub = pub.Replace("出版者 : </td>\n<td>", "");
                }
                pub = "";
            }
            else
            {
                if (str.Contains("出版者"))
                {
                    pub = str = str.Substring(str.IndexOf("出版者 : "));
                    tmp = pub.Substring(pub.IndexOf("</td>\n</tr>\n<tr>"));
                    pub = pub.Replace(tmp, "");
                    pub = pub.Replace("出版者 : </td>\n<td>", "");
                }
                pub = "";
            }
            //pub = pub.Substring(pub.IndexOf("</td>\n<td>") + 10);
            //tmp = pub.Substring(pub.IndexOf("</td>\n</tr>"));
            //pub = pub.Replace(tmp, "");

            string isbn;
            if (str.Contains("主题词"))
            {
                isbn = str = str.Substring(str.IndexOf("标准书号 : "));
                tmp = isbn.Substring(isbn.IndexOf("主题词 : "));
                isbn = isbn.Replace(tmp, "");
                isbn = isbn.Substring(isbn.IndexOf("</td>\n<td>") + 10);
                tmp = isbn.Substring(isbn.IndexOf("</td>\n</tr>"));
                isbn = isbn.Replace(tmp, "");
            }
            else if (str.Contains("标准书号"))
            {
                string p = str = str.Substring(str.IndexOf("标准书号 : </td>\n<td>") + 17);
                tmp = p.Substring(p.IndexOf("</td>"));
                isbn = p.Replace(tmp, "");
            }
            else
            {
                isbn = "";
            }
            try
            {
                string[] isbnarray = Regex.Split(isbn.Replace("&nbsp;", ""), ",");
                if (isbnarray.Length == 1)
                    isbn = isbn.Replace("&nbsp;", "").Replace("-", "");
                else
                    isbn = isbnarray[0].Replace("-", "");
                if (isbn.Contains("不详"))
                    isbn = null;
            }
            catch
            {
                isbn = null;
            }
            string limg = "", mimg = "", simg = "", summary = "", pages = "", price = "", alt = "";
            RatingInfo rate = new RatingInfo();
            if (isbn != null && isbn != "" && Request.Params["detail"] == "true")
            {
                try
                {
                    //WebRequest re = WebRequest.Create("https://api.douban.com/v2/book/isbn/" + isbn);
                    DataSet.DataDataTable table = new DataSet.DataDataTable();
                    DataSetTableAdapters.DataTableAdapter adapter = new DataSetTableAdapters.DataTableAdapter();
                    table = adapter.GetDataByISBN(isbn);
                    string st;
                    if (table.Count == 0)
                    {
                        WebRequest re = WebRequest.Create("http://xiyoumobiledouban.duapp.com/?isbn=" + isbn);
                        WebResponse rp = re.GetResponse();
                        Stream sr = rp.GetResponseStream();
                        StreamReader read = new StreamReader(sr);
                        st = read.ReadToEnd();
                        adapter.InsertInfo(isbn, st);
                    }
                    else
                    {
                        st = table[0].Douban_JSON;
                    }
                    JObject data = JObject.Parse(st);
                    limg = (string)data["images"]["large"];
                    mimg = (string)data["images"]["medium"];
                    simg = (string)data["images"]["small"];
                    price = (string)data["price"];
                    pages =(string)data["pages"];
                    pub = (string)data["publisher"];
                    summary = (string)data["summary"];
                    alt = (string)data["alt"];
                    rate.Heighest = (int)data["rating"]["max"];
                    rate.Lowest = (int)data["rating"]["min"];
                    rate.Avg = Convert.ToDouble((string)data["rating"]["average"]);
                    rate.Times = (int)data["rating"]["numRaters"];
                }
                catch
                {
                    limg = ""; mimg = ""; simg = ""; summary = ""; pages = ""; price = ""; alt = "";
                }
            }

            if (str.Contains("主题词"))
            {
                string keyword = str = str.Substring(str.IndexOf("主题词 : </td>\n<td>") + 16);
                tmp = keyword.Substring(keyword.IndexOf("</td>"));
                keyword = keyword.Replace(tmp, "");
            }

            str = str.Substring(str.IndexOf("附件信息"));
            str = str.Replace("\t", "");
            str = str.Replace("\n", "");
            str = str.Replace("\r", "");

            str = str.Substring(str.IndexOf("<td align=center>"));
            tmp = str.Substring(str.IndexOf("<br>"));
            str = str.Replace(tmp, "");
            temp = Regex.Split(str, "<td align=center>");
            List<BookCirculation> BookCirculationData = new List<BookCirculation>();
            string Number = "";
            for (int i = 1; i < temp.Length; i++)
            {
                tmp = temp[i].Replace("</td>", "");
                tmp = tmp.Replace("        ", "");
                tmp = tmp.Replace("    ", "");
                string[] t = Regex.Split(tmp, "<td>");
                if (Number == "")
                    Number = t[2];
                BookCirculationData.Add(new BookCirculation
                {
                    Barcode = t[1],
                    Department = t[4],
                    State = t[5],
                    Date = t[6]
                });
            }
            if (author != "")
            {
                author = author.Trim();
                if (author[author.Length - 1] == ',')
                {
                    author = author.Substring(0, author.Length - 1);
                }
            }
            object bkdata;
            if (isbn != null && isbn != "" && Request.Params["detail"] == "true")
            {
                bkdata = new BookDetailWithDouban
               {
                   CtrlID = id,
                   ID = Number,
                   Author = author,
                   Title = title,
                   Pub = pub,
                   Info = BookCirculationData,
                   image_l = limg,
                   image_m = mimg,
                   image_s = simg,
                   Summary = summary,
                   Price = price,
                   Pages = pages,
                   ISBN = isbn,
                   Link = alt,
                   Rating = rate,
               };
            }
            else
            {
                bkdata = new BookDetail
               {
                   CtrlID = id,
                   ID = Number,
                   Author = author,
                   Title = title,
                   Pub = pub,
                   Info = BookCirculationData,
                   ISBN = isbn
               };
            }
            JavaScriptSerializer jsondata = new JavaScriptSerializer();
            Response.Write(jsondata.Serialize(bkdata));
        }
    }
}